package com.qf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.constans.SystemParameter;
import com.qf.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 记录每个用户的每个接口的剩余调用次数
 */

@Component
public class LimitFilter extends ZuulFilter {

    @Resource
    private RedisService redisService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 50;
    }

    @Override
    public boolean shouldFilter() {
        //在执行校验某个用户的某个接口的剩余调用次数时，先判断该接口是否设置了次数限制（limit==1?限制次数：不限制次数）
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String method = request.getParameter("method");
        Map<Object, Object> apiinfoMap = SystemParameter.apiinfoMap;
        Map map = (Map) apiinfoMap.get(SystemParameter.REDISAPIPRE + ":" + method);
        return RequestContext.getCurrentContext().sendZuulResponse()&&"1".equalsIgnoreCase(map.get("limit").toString());
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String appkey = request.getParameter("appkey");
        String method = request.getParameter("method");

        Long hincr = redisService.hincr(SystemParameter.APINUM + appkey, method, -1l);

        if (hincr<0){
            currentContext.getResponse().setContentType("text/html;charset=utf-8");
            currentContext.setResponseBody("您的免费次数已经用完！");
            currentContext.setSendZuulResponse(false);
        }
        return null;
    }
}
